<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
      <el-form-item label="设备名称" prop="equName" label-width="100px">
        <el-input v-model="queryParams.equName" placeholder="请输入设备名称" clearable style="width: 240px"
          @keyup.enter="handleQuery" @clear="handleQuery" @input="handleInput" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" size="large" :data="roleList" row-key="id" :indent="50" :max-height="tableHeight">
      <el-table-column type="index" label="序号" width="120" align="center">
        <template #default="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备名称" v-if="columns[0].visible" prop="equName" align="center" width="200" />
      <el-table-column label="设备描述" v-if="columns[1].visible" prop="equDes" :show-overflow-tooltip="false"
        align="center" width="200" />
      <el-table-column label="设备位置" v-if="columns[2].visible" align="left" width="180">
        <template #default="scope">
          <div v-for="(position, index) in scope.row.position" :key="index">
            <el-tooltip placement="top" :disabled="position.poName?.length < 8" :content="position.poName">
              <el-tag closable type="warning" @close="handleTagClose(position)" class="custom-tag">
                {{ position.poName }}
              </el-tag>
            </el-tooltip>
          </div>
          <el-button class="button-new-tag" link type="primary" size="small" @click="handleUpdate2(scope.row)">
            + 添加位置
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="所属企业" v-if="columns[3].visible" prop="comName" align="center" width="250" />
      <el-table-column label="所属部门" v-if="columns[4].visible" prop="departName" align="center" width="250" />
      <el-table-column label="创建时间" v-if="columns[5].visible" align="center" width="200">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" min-width="260px" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="success" icon="View" :disabled="!scope.row.position || scope.row.position.length === 0"
            @click="handleViewPositions(scope.row)">
            查看位置
          </el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属企业" prop="entID">
          <el-select v-model="form.entID" placeholder="请选择所属企业" @change="handleEntChange">
            <el-option v-for="item in options2" :key="item.id" :label="item.companyName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门" prop="departID">
          <el-cascader style="width: 600px;" ref="cascaderRef" @change="handleCascaderChange" v-model="form.departID"
            :options="options3"
            :props="{ checkStrictly: true, children: 'children', label: 'partName', value: 'id', emitPath: false }" />
        </el-form-item>
        <el-form-item label="设备名称" prop="equName">
          <el-input v-model.trim="form.equName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备描述" prop="equDes">
          <el-input v-model="form.equDes" type="textarea" :maxlength="100" placeholder="请输入设备描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title2" v-model="open2" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="roleRef2" :model="form2" :rules="rules2" label-width="100px">
        <el-form-item label="设备位置" prop="poName">
          <el-input v-model.trim="form2.poName" placeholder="请输入监控位置" maxlength="30" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm2">确 定</el-button>
          <el-button @click="open2 = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查看设备位置列表弹窗 -->
    <el-dialog :title="title3" v-model="open3" width="800px" append-to-body :close-on-click-modal="false">
      <div class="position-list-container">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd2">新增位置</el-button>
          </el-col>
        </el-row>
        <el-table :data="positionList" style="width: 100%" max-height="400">
          <el-table-column type="index" label="序号" width="60" align="center">
            <template #default="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="位置名称" prop="poName" align="center" min-width="150">
            <template #default="scope">
              <span>{{ scope.row.poName || '' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="绑定的传感器" align="center" min-width="250">
            <template #default="scope">
              <div v-if="scope.row.devID" class="sensor-tags">
                <el-tag size="small" class="sensor-tag">
                  {{ scope.row.poDes }}
                </el-tag>
              </div>
              <div v-else>
                <span class="no-sensor">未绑定传感器</span>
                <el-button type="success" round size="small" @click="handleBindSensor(scope.row)">去绑定</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="在线状态"  align="center" width="100" >
            <template #default="scope" >
              <span :class="[scope.row.state === 1?'online':'offline']" v-if="scope.row.devID">
                {{ scope.row.state === 1 ? '在线' : '离线' }}
              </span>
            </template>
          </el-table-column>
        </el-table>
        <!-- 空状态 -->
        <div v-if="!positionList || positionList.length === 0" class="empty-state">
          <el-empty description="该设备暂无位置信息" />
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="open3 = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 绑定传感器 -->
    <el-dialog title="绑定传感器" v-model="open4" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="roleRef4" :model="form4" :rules="rules4" label-width="120px">
        <el-form-item label="设备位置名称" prop="poName">
          <el-input v-model.trim="form4.poName" placeholder="设备位置名称" maxlength="50" />
        </el-form-item>
        <el-form-item label="选择传感器" prop="devID">
          <el-select v-model="form4.devID" filterable placeholder="可搜索传感器名称">
            <el-option v-for="item in options4" :key="item.id" :label="item.name" :disabled="!!item.isLocked" :value="item.id">
              <span style="float: left">{{ item.name }}</span><span v-if="item.isLocked" style="font-size: 11px;" >（已绑定）</span>
              <span style=" float: right; color: var(--el-text-color-secondary); font-size: 13px; ">
                {{ item.imei }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm4">确 定</el-button>
          <el-button @click="open4 = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { useInfoStore } from '@/store/modules/info.js'
const userInfo = useInfoStore();
const tableHeight = ref(document.documentElement.scrollHeight - 280 + "px");
const { proxy } = getCurrentInstance();
const roleList = ref([]);
const open = ref(false);
const open2 = ref(false);
const open3 = ref(false); // 查看位置列表弹窗
const open4 = ref(false); // 查看位置列表弹窗
const loading = ref(false);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const title2 = ref("");
const title3 = ref(""); // 查看位置列表弹窗标题
const options2 = ref([]);
const positionList = ref([]); // 位置列表数据
const data = reactive({
  form: {
    id: null,
    entID: null,
    departID: null, //部门id
    equName: null,//设备机械名称
    equDes: null,//设备机械描述
    alarmTime: 0
  },
  form2: {
    id: null,
    equID: null, //机械id
    poName: null, //监控位置
    poDes: null,//监控位置说明
    devID: null,//设备
    state: 1
  },
  form4: {
    id:null,//机械-位置id
    poName: null, //监控位置
    devID: null,//传感器id
  },
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    entID: null,
    partName: null,
  },
  rules: {
    entID: [{ required: true, message: "所属企业不能为空", trigger: "blur" }],
    departID: [{ required: true, message: "所属部门不能为空", trigger: "blur" }],
    equName: [{ required: true, message: "设备名称不能为空", trigger: "blur" }],
  },
  rules2: {
    poName: [{ required: true, message: "设备位置不能为空", trigger: "blur" }],
  },
  rules4: {
    poName: [{ required: true, message: "设备位置不能为空", trigger: "blur" }],
    devID: [{ required: true, message: "传感器不能为空", trigger: "change" }],
  },
});
const cascaderRef = ref(null);
const options3 = ref([]);
const options4 = ref([]);
const _item = ref(null);
// 列显隐信息
const columns = ref([
  { key: 0, label: `设备名称`, visible: true },
  { key: 1, label: `设备描述`, visible: true },
  { key: 2, label: `设备位置`, visible: true },
  { key: 3, label: `所属企业`, visible: true },
  { key: 4, label: `所属部门`, visible: true },
  { key: 5, label: `创建时间`, visible: true },
]);

const { queryParams, form, form2,form4, rules, rules2, rules4} = toRefs(data);

/** 查询企业列表下拉 */
function getGetEnterpriseList() {
  proxy.cloudTv_API.GetListCom({}).then(response => {
    if (response.data) {
      options2.value = response.data || [];
    }
  });
}
// 企业下拉选择
function handleEntChange(value) {
  _GetListDepart();
}
/** 查询部门列表下拉 */
function _GetListDepart(flag = false) {
  proxy.cloudTv_API.GetListDepart({ entID: form.value.entID }).then(response => {
    if (response.data?.length > 0) {
      options3.value = response.data;
      form.value.departID = form.value.departID ? form.value.departID : options3.value[0].id;
    } else {
      options3.value = [];
      proxy.$modal.msgWarning("当前企业还没有添加部门~");
    }
  });
}
/** 查询列表 */
function getList() {
  loading.value = true;
  proxy.cloudTv_API.GetPageListEqui(queryParams.value).then(response => {
    roleList.value = response.data.list;
    total.value = response.data.total || 0;
    loading.value = false;
  });
}
/**
 * 处理标签关闭事件
 * @param {Object} row - 当前行数据
 * @param {number} index - 标签在 position 数组中的索引
 */
function handleTagClose(row, index) {
  proxy.$modal.confirm('是否确认删除位置名称"' + row.poName + '"的数据项?').then(function () {
    proxy.cloudTv_API.DelPosi({ id: row.id }).then(response => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    });
  })

}
// 主动关闭弹层
function handleCascaderChange(e) {
  // 获取当前选中的节点列表
  const item = cascaderRef.value.getCheckedNodes()[0].data;
  form.value.departID = item?.id;
  cascaderRef.value.togglePopperVisible(false)
}
// 输入时触发的防抖处理函数
let timer = null;
function handleInput() {
  clearTimeout(timer);
  timer = setTimeout(handleQuery, 300);
}

/** 位置绑定传感器 */
function handleBindSensor(row){
  proxy.cloudTv_API.GetListDev({}).then(response => {
    options4.value = response.data || [];
  });
  form4.value.id = row.id;// 机械-位置id
  form4.value.poName = row.poName;// 机械-位置id
  console.log(form4.value);
  open3.value = false;
  nextTick(() => {
     open4.value = true;
  })
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNo = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除设备名称"' + row.equName + '"的数据项?').then(function () {
    proxy.cloudTv_API.DelEqui({ id: row.id }).then(response => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    });
  })
}

/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    id: null,
    entID: null,
    departID: null, //部门id
    equName: null,//设备机械名称
    equDes: null,//设备机械描述
    alarmTime: 0
  };
  // 添加默认第一个
  form.value.entID = form.value.entID ? form.value.entID : options2.value[0].id;
  proxy.resetForm("roleRef");
}

/** 添加 */
function handleAdd() {
  reset();
  _GetListDepart();
  open.value = true;
  title.value = "新增";
}
/** 添加位置 */
function handleAdd2() {
  open3.value = false;
  nextTick(() => {
    handleUpdate2(_item.value);
  })
}

/** 查看设备位置列表 */
function handleViewPositions(row) {
  _item.value = row;
  // 设置弹窗标题
  title3.value = `${row.equName} - 位置列表`;
  // 处理位置数据
  positionList.value =row.position ;
  open3.value = true;
}

/** 添加下级 */
function handleUpdate2(row) {
  form2.value = {
    equID: row.id, // 机械id
    poName: null, //监控位置
    poDes: null,//监控位置说明
    devID: null,//设备
    state: 1
  }
  open2.value = true;
  title2.value = row.equName + ' - 新增位置信息';
}
/** 修改 */
function handleUpdate(row) {
  reset();
  // 填充表单数据
  Object.keys(form.value).forEach(key => {
    form.value[key] = row[key];
    if (form.value[key] == undefined) {
      form.value[key] = null
    }
  });
  form.value.entID = row.comID;
  _GetListDepart();
  open.value = true;
  title.value = "修改";
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["roleRef"].validate(valid => {
    if (valid) {
      if (form.value.id) {
        proxy.cloudTv_API.UpdateEqui({
          ...form.value,
        }).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        proxy.cloudTv_API.AddEqui(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 提交按钮 */
function submitForm2() {
  proxy.$refs["roleRef2"].validate(valid => {
    if (valid) {
      proxy.cloudTv_API.AddPosi(form2.value).then(response => {
        proxy.$modal.msgSuccess("添加成功");
        open2.value = false;
        getList();
      });
    }
  });
}
/** 提交按钮 */
function submitForm4() {
  proxy.$refs["roleRef4"].validate(valid => {
    if (valid) {
      proxy.cloudTv_API.UpdatePosi(form4.value).then(response => {
        proxy.$modal.msgSuccess("绑定成功");
        open4.value = false;
        getList();
      });
    }
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
getGetEnterpriseList();
getList();
</script>

<style lang="scss" scoped>
:deep(.el-table__expand-icon .el-icon) {
  font-size: 14px !important;
}

.custom-tag {
  width: 120px; // 限制最大宽度
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-flex; // 使用 flex 布局
  align-items: center;
  margin-bottom: 8px;

  :deep(.el-tag__content) {
    max-width: calc(100% - 20px); // 减去关闭图标宽度
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.button-new-tag {
  width: 120px; // 限制最大宽度
}

/* 位置列表弹窗样式 */
.position-list-container {
  text-align: center;
  .sensor-tag{
    max-width: 400px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .no-sensor{
    color: #999;
    font-size: 12px;
    margin-right: 4px;
    display: inline-block;
  }
}


/* 禁用按钮样式 */
:deep(.el-button.is-disabled) {
  opacity: 0.5;
  cursor: not-allowed;
}
.online {
  color: #67C23A;
}

.offline {
  color: #F56C6C;
}
</style>